﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DropBoxTool.Model;
using Microsoft.Phone.Controls;

namespace DropBoxTool
{
    public partial class ImageViewer : ViewModelPageClassWithQuery
    {
        public ImageViewer()
        {
            InitializeComponent();
            if (IsInDesignMode)
            {
                File = new NavigatableDropBoxFolderItem
                {
                    FullPath = "testing\testing file.jpg",
                    IsDirectory = false
                };
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (!IsInDesignMode)
            {
                // TODO: load Image
                var fullPath = QueryString["file"] ?? "";
                LoadImage(fullPath);
            }
        }

        private void LoadImage(string fullPath)
        {
            Message = "";
            if (!String.IsNullOrEmpty(fullPath))
            {
                progressIndicator.Visibility = Visibility.Visible;
                DropBoxController.Inst.Api.GetFile(fullPath, (isoPath, ex) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (ex == null)
                        {
                            var lastResult = DropBoxController.Inst.Api.GetLastListingResults(fullPath);
                            file = NavigatableDropBoxFolderItem.FromBaseType(lastResult);

                            using (var isoFS = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                if (isoFS.FileExists(isoPath))
                                {
                                    using (var fs = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(isoPath, FileMode.Open))
                                    {
                                        BitmapImage bmp = new BitmapImage();
                                        bmp.SetSource(fs);
                                        pictureViewer.Source = bmp;
                                    }
                                }
                                else
                                {
                                    // TODO: notify user no file
                                    Message = "FYI: File not downloaded yet (Network may be down)";
                                }
                            }
                            if (FolderInfo == null)
                            {
                                //var arrPath = fullPath.Split('/');
                                //var parentsPath = string.Join("/", arrPath.Take(arrPath.Length - 1).ToArray()) + "/";

                                FolderInfo = NavigatableDropBoxFolderItem.FromBaseType(
                                    DropBoxController.Inst.Api.GetLastListingResults(file.FilePath));
                            }
                        }
                        else
                        {
                            // TODO: notify the user of an error
                            Message = "FYI: An error occurred while trying to get this file (Network might have just gone down)";
                        }

                        progressIndicator.Visibility = Visibility.Collapsed;
                    });
                });
            }
        }

        private NavigatableDropBoxFolderItem folderInfo = null;

        public NavigatableDropBoxFolderItem FolderInfo
        {
            get
            {
                return folderInfo;
            }
            set
            {
                folderInfo = value;
                RaisePropertyChanged("FolderInfo");
            }
        }

        protected string message = "";

        public string Message
        {
            get { return message; }
            set
            {
                message = value;
                RaisePropertyChanged("Message");
            }
        }

        protected NavigatableDropBoxFolderItem file = null;

        public NavigatableDropBoxFolderItem File
        {
            get { return file; }
            set
            {
                file = value;
                RaisePropertyChanged("File");
            }
        }

        private void PrevImageButton_Click(object sender, System.EventArgs e)
        {
            var q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.imageTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1 &&
                     fileItem.Name.CompareTo(file.Name) < 0
                     orderby fileItem.Name descending
                     select fileItem).FirstOrDefault();
            if (q == null)
            {
                q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.imageTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1
                     orderby fileItem.Name
                     select fileItem).LastOrDefault();
            }

            if (q != null)
            {
                LoadImage(q.FullPath);
            }
        }

        private void NextImageButton_Click(object sender, System.EventArgs e)
        {
            var q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.imageTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1 &&
                     fileItem.Name.CompareTo(file.Name) > 0
                     orderby fileItem.Name
                     select fileItem).FirstOrDefault();
            if (q == null)
            {
                q = (from fileItem in folderInfo.Contents
                     where Array.IndexOf(NavigatableDropBoxFolderItem.imageTypes, System.IO.Path.GetExtension(fileItem.FullPath).ToUpper()) != -1
                     orderby fileItem.Name
                     select fileItem).FirstOrDefault();
            }

            if (q != null)
            {
                LoadImage(q.FullPath);
            }
        }
    }
}